/** Cluster application **/
/* MPPA headers */
#include <mppaipc.h>
#include <mppa/osconfig.h>

#include <stdlib.h>
#include <stdio.h>
#include <string.h>

#define UNLIMIT
#define MAXARRAY 2 /* this number, if too large, will cause a seg. fault!! */

struct myStringStruct {
  char qstring[128];
};

int compare(const void *elem1, const void *elem2)
{
  int result;
  
  result = strcmp((*((struct myStringStruct *)elem1)).qstring, (*((struct myStringStruct *)elem2)).qstring);

  return (result < 0) ? 1 : ((result == 0) ? 0 : -1);
}


int usr_main(int argc, const char *argv) {
  struct myStringStruct array[MAXARRAY];
  FILE *fp;
  int count=0;
  
  if (argc<2) {
    //fprintf(stderr,"Usage: qsort_small <file>\n");
    exit(-1);
  }
  else {
    const char* permission = "r";
    fp = fopen(argv, permission);    
    const char* type = "%s";
    while((fscanf(fp, type, &array[count].qstring) == 1) && (count < MAXARRAY)) {
       count++;
    }
    fclose(fp);
  }
  //printf("\nSorting %d elements.\n\n",count);
  //qsort(array,count,sizeof(struct myStringStruct),compare);
  
  //for(i=0;i<count;i++)
    //printf("%s\n", array[i].qstring);
  return 0;
}


//#define MPPA_TRACEPOINT_DEFINE
//#include "test-trace.h"

//#define MPPA_CREATE_TRACEPOINT
//#include "mppa_trace.h"


int main(int argc, char* argv[]) {
//mppa_trace_init();
//mppa_tracepoint(test,tp99__in);
	// get arguments
	int rank = atoi(argv[0]);
        const char *global_sync = argv[1], *results_portal = argv[2];
	
	// set mask (e.g. 1000..0) 
	long long mask = (long long)1 << rank;

	// open Wx connectors	
	int global_sync_fd = mppa_open(global_sync, O_WRONLY);
        int results_portal_fd = mppa_open(results_portal, O_WRONLY);

	// contributes to unblock the I/O, writes on sync with the mask value
	mppa_write(global_sync_fd, &mask, sizeof(mask));

//mppa_trace_init();

// START CODE HERE

    int results = usr_main(2, "\home\ismac\p-socrates_training\pWCET\MyQsort\input_small.dat");
    
    
   
	// writes on the portal
	// 	- results_portal_fd = portal descriptor
	// 	- results = data to transfer to the I/O
	// 	- size of data to send
	// 	- position of data on the Rx memory (at I/O)
	

	mppa_pwrite(results_portal_fd, &results, sizeof(long int), sizeof(long int)*rank);
//mppa_tracepoint(test,tp99__out);
}
